<script setup>
import _ from 'lodash'
import {ResizeObserver} from 'vue3-resize'
import {useCommonStore} from "@jzl/stores";
import {computed, nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";
import {$WinDeptUsers} from "@jzl/comps-mg";
import {DFT_ICONS} from "@jzl/icons";

const {
  items,
  loading,
  currentData,
  posts,
  datasTableHeight,
} = toRefs(reactive({
  items: [],
  loading: false,
  currentData: {},
  posts: [],
  datasTableHeight: 500,
}))
const datasContainerRef = ref(null)
const project = computed(() => {
  return useCommonStore().project;
})

watch(() => project.value, () => {
  init();
})

onMounted(() => {
  init()
})

const init = async () => {
  // let iProject = _.cloneDeep(project.value);
  let depts = await api.dept.getDeptMatrixTree();

  // if(!project) return;
  //
  // project.dept_name = _.get(project, 'project_name');
  // project.isRoot = true;
  // project.dept_id = -1;
  // project.subs = depts;

  loading.value = true;

  await initPosts();
  items.value = depts;     // [ project ];
  handleResize();

  loading.value = false;
}

const initPosts = async () => {
  let postList = await api.dept.getDeptMatrixPosts();

  _.each(postList, p => {
    p.isCreate = false
  });

  posts.value = postList;
}

const handleResize = () => {
  nextTick(() => {
    if (!datasContainerRef.value) return;

    let rect = datasContainerRef.value.getBoundingClientRect();
    let height = _.get(rect, 'height');
    if (height > 0) {
      datasTableHeight.value = height;
    }
  });
}

const handleShowAddUser = (dept, deptPostId) => {

  let deptId = _.get(dept, 'dept_id');
  if (!deptId || !deptPostId) return;

  $WinDeptUsers({
    mode: 'USER',
    onConfirm: async (data) => {
      let users = _.get(data, 'users');
      let ids = _.map(users, 'id');

      loading.value = true;

      let ret = await api.dept.deptMatrixAssignUsers(deptId, deptPostId, ids);

      if (ret) {
        let deptNew = await api.dept.getDeptMatrixDept(deptId);

        if (deptNew && deptNew.items) dept.items = deptNew.items;
      }

      loading.value = false;
    }
  });
}

const handleRemoveUser = async (dept, urel) => {
  let id = _.get(urel, 'id');
  let deptId = _.get(dept, 'dept_id');
  if (!id) return;

  let ids = [id];
  let ret = await api.dept.deptMatrixRemoveUsers(ids);

  if (ret) {
    let deptNew = await api.dept.getDeptMatrixDept(deptId);
    if (deptNew && deptNew.items) dept.items = deptNew.items;
  }
}

const handleShowCreatePost = async () => {
  posts.value.push({
    dept_post_name: '',
    isCreate: true
  });
}

const handleShowDeletePost = async (head) => {
  let msg = `删除将不能回复，确定删除当前维度：${head.dept_post_name}？`;
  $jui.confirm(msg, '提示').then(async () => {
    let ret = await api.dept.deptMatrixPostRemove(head.dept_post_id);

    if (ret) {
      await initPosts();
    }
  });
}

const handleChangePostName = async (h, idx) => {
  if (!h) return;

  if (h.isCreate && !h.dept_post_name) {
    return posts.value.splice(idx, 1);
  }

  // 修改
  if (h.dept_post_id) {
    await api.dept.deptMatrixPostUpdate(h.dept_post_id, h);
    await initPosts();
  } else if (h.isCreate) {
    h.isCreate = false;
    await api.dept.deptMatrixPostCreate(h);
    await init();
  }
}

const handleBlurPostName = async (h, idx) => {
  if (!h) return;

  if (h.isCreate && !h.dept_post_name) {
    posts.value.splice(idx, 1);
  }

  h.isCreate = false;
}

const handleEnterPostName = (h, idx) => {
  handleBlurPostName(h, idx);
  h.create = false;
}

const handleShowEditPost = (h, idx) => {
  if (!h) return;
  h.isCreate = true;
}
</script>

<template>
  <div class="mb-wrap">
    <div class="m-table-container dept-matrix" ref="datasContainerRef">
      <el-table
        :data="items"
        row-key="dept_id"
        :tree-props="{ children: 'subs' }"
        v-loading="loading"
        :height="datasTableHeight"
        class="m-table m-table-ns"
        border
        default-expand-all>
        <el-table-column
          prop="name"
          label="部门名称"
          class-name="dept-name">
          <template #header="scope">
            <span style="display:inline-block;width:5px;height:20px;"></span>部门名称
          </template>
          <template #default="scope">
            <span style="display:inline-block;width:3px;" v-if="!scope.row.subs || !scope.row.subs.length"></span>
            <span>{{ scope.row.dept_name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="h.dept_post_name"
          v-for="(h, idx) in posts"
          :style="{ width: h.isCreate ? '120px': 'auto' }">
          <template #header="scope">
            <div class="dept-matrix-header-wrap">
              <el-input
                v-if="h.isCreate"
                v-model="h.dept_post_name"
                v-focus
                class="dept-matrix-input"
                placeholder="请输入维度名称"
                @change="handleChangePostName(h, idx)"
                @blur="handleBlurPostName(h, idx)"
                @keyup.native.enter="handleEnterPostName(h, idx)"></el-input>
              <span
                v-else
                class="dept-matrix-header"
                @click.stop="handleShowEditPost(h, idx)"
              >{{ h.dept_post_name }}
                <JIcon
                  :icon="DFT_ICONS.error"
                  @click.stop="handleShowDeletePost(h)"
                  v-tippy="{arrow: true}"
                  content="删除当前维度"
                />
              </span>
            </div>
          </template>
          <template #default="scope">
            <div class="dept-matrix-users">
              <div>
                <el-tag
                  class="user-tag"
                  v-for="u in scope.row.items[ h.dept_post_id ]"
                  closable
                  @close="handleRemoveUser(scope.row, u)">{{ u.admin.nickname }}
                </el-tag>
              </div>
              <el-button
                class="user-tag user-add-btn"
                size="small"
                plain
                type="primary"
                @click="handleShowAddUser(scope.row, h.dept_post_id)">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.add"/>
                </template>添加
              </el-button>
            </div>
            <!--                        {{scope.row.posts[ h.dept_post_id ]}}-->
          </template>
        </el-table-column>
        <el-table-column
          prop="remark1"
          label="操作"
          width="60"
          align="center"
          class-name="dept-matrix-create">
          <template #header="scope">
            <el-button
              size="small"
              type="text"
              @click="handleShowCreatePost()">
              <template #icon>
                <JIcon :icon="DFT_ICONS.add"/>
              </template>维度
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <ResizeObserver @notify="handleResize"/>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.m-table-container {
  width: 100%;
  margin: 0px;
}

.mb-wrap {
  display: flex;
  height: 100%;
  background: #FFF;

  .role-menu-item {
    margin-right: 10px;

    &.border {
      border: 1px solid #EEE;
    }
  }
}

.dept-matrix {
  .m-table {
    td {
      padding: 8px 0;
    }
  }

  .dept-name {
    background: #fcfcfc;
    border-right: 1px solid #F1F1F1;
  }

  .dept-matrix-header-wrap {
    height: 28px;
  }

  .dept-matrix-header {
    margin-right: 20px;
    padding: 0 5px;
    position: relative;
    cursor: pointer;
    line-height: 26px;
    display: inline-block;
    min-width: 100px;

    i {
      opacity: 0;
      position: absolute;
      right: -15px;
      top: 6px;
      font-size: 14px;
      transition: all .2s;
    }

    &:hover {
      color: #409eff;
      border-bottom: 1px dashed #409eff;

      i {
        opacity: 1;
      }
    }
  }

  .dept-matrix-users {
    width: 100%;
    min-height: 20px;
    /*padding-right: 30px;*/
    display: flex;

    &:hover {
      .user-add-btn {
        opacity: 1;
      }
    }
  }

  .user-tag {
    margin: 2px 3px;
    transition: all .1s;

    &.user-add-btn {
      height: 23px;
      line-height: 1;
      padding: 0px 8px 0px 5px;
      opacity: 0;
    }
  }

}
</style>
<style lang="scss">
.dept-matrix-input {
  .el-input__wrapper {
    box-shadow: none;
    border-left: none;
    border-right: none;
    border-top: none;
    padding-left: 10px;
  }
  .el-input__inner {
    height: 26px;
  }
}

.dept-matrix th.dept-matrix-create {
  .cell {
    padding: 0px;
  }
}
</style>
